import { debounce, observerDomResize } from './index'

export default {
  data () {
    return {
      dom: '',
      width: 0,
      height: 0,
      debounceInitWHFun: '',
      domObserver: ''
    }
  },
  methods: {
    async autoResizeMixinInit () {
      this.dom = document.body
      await this.initWH(false)//初始化容器的长宽和容器dom
      this.getDebounceInitWHFun()
      this.bindDomResizeCallback()
      if (typeof this.afterAutoResizeMixinInit === 'function')
        this.afterAutoResizeMixinInit()
    },
    initWH (resize = true) {
      return new Promise(resolve => {
        if (typeof this.onResize === 'function' && resize) this.onResize()
        resolve()
      })
    },
    getDebounceInitWHFun () {
      const { initWH } = this
      this.debounceInitWHFun = debounce(initWH,100)
    },
    bindDomResizeCallback () {
      const { dom, debounceInitWHFun } = this

      this.domObserver = observerDomResize(dom, debounceInitWHFun)

      window.addEventListener('resize', debounceInitWHFun)
    },
    unbindDomResizeCallback () {
      let { domObserver, debounceInitWHFun } = this
      if (!domObserver) return
      domObserver.disconnect()
      domObserver.takeRecords()
      domObserver = null
      window.removeEventListener('resize', debounceInitWHFun)
    },
    afterAutoResizeMixinInit () {
      this.initConfig()
      this.setAppScale()
    },
    initConfig () {
      const bl = this.$scale()
      this.dom.style.width = `${document.documentElement.clientWidth/bl}px`
      this.dom.style.height = `${document.documentElement.clientHeight/bl}px`
    },
    setAppScale () {
      this.dom.style.transform = `scale(${this.$scale()})`
    },
    onResize () {
      this.setAppScale()
    }
  },
 async mounted () {
   this.autoResizeMixinInit()
  },
  beforeDestroy () {
    const { unbindDomResizeCallback } = this
    unbindDomResizeCallback()
  }
}
